package cn.tedu.recruitmentwebsite.common.controller;

import cn.tedu.recruitmentwebsite.admin.pojo.dto.UserQuery;
import cn.tedu.recruitmentwebsite.base.constant.JwtClaimsConstant;
import cn.tedu.recruitmentwebsite.base.pojo.dto.UpdatePasswordParam;
import cn.tedu.recruitmentwebsite.base.pojo.dto.UserLoginParam;
import cn.tedu.recruitmentwebsite.base.pojo.dto.UserSaveParam;
import cn.tedu.recruitmentwebsite.base.pojo.entity.User;
import cn.tedu.recruitmentwebsite.base.pojo.vo.UserVO;
import cn.tedu.recruitmentwebsite.base.properties.JwtProperties;
import cn.tedu.recruitmentwebsite.base.response.JsonResult;

import cn.tedu.recruitmentwebsite.base.util.AliOssUtil;
import cn.tedu.recruitmentwebsite.base.util.JwtUtil;
import cn.tedu.recruitmentwebsite.common.service.CommonService;
import cn.tedu.recruitmentwebsite.common.service.VerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Autowired
    private CommonService commonService;
    @Autowired
    private VerificationCodeService verificationCodeService;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private JwtProperties jwtProperties;
    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam) {
        log.debug("用户登录，参数：{}", userLoginParam);
        User user = commonService.login(userLoginParam);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);
        UserVO userVO = UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .gender(user.getGender())
                .email(user.getEmail())
                .role(user.getRole())
                .createTime(user.getCreateTime())
                .updateTime(user.getUpdateTime())
                .lastLoginTime(user.getLastLoginTime())
                .userStatus(user.getUserStatus())
                .token(token).build();
        log.debug("用户登录成功，返回：{}", userVO);
        return JsonResult.ok(userVO);
    }
    @PostMapping("/verifyCode")
    public JsonResult verifyCode(@RequestBody Map<String, String> requestBody) {
        String phoneNumber = requestBody.get("phoneNumber");
        String inputCode = requestBody.get("verificationCode");

        if (verificationCodeService.verifyCode(phoneNumber, inputCode)) {
            return JsonResult.ok("验证码验证成功");
        } else {
            return JsonResult.ok("验证码错误");
        }
    }
    @PostMapping("/reg")
    public JsonResult reg(@RequestBody UserSaveParam userSaveParam ) {
        log.info("用户注册，参数：{}", userSaveParam);
        commonService.reg(userSaveParam);
        return JsonResult.ok();
    }
    @PostMapping("/logout")
    public JsonResult logout(@RequestBody UserQuery userQuery) {
        log.info("用户退出登录，参数：{}", userQuery);
        try {
            commonService.updateLastLoginTime(userQuery.getId());
            return JsonResult.ok("退出登录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.ok("退出登录失败");
        }
    }
    @PostMapping("change-password")
    public JsonResult changePassword(@RequestBody UpdatePasswordParam updatePasswordParam) {
        log.info("修改密码，参数：{}", updatePasswordParam);
         commonService.changePassword(updatePasswordParam);
        return JsonResult.ok();
    }
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file){
        log.info("文件上传：{}",file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
                log.debug("文件上传成功，文件请求路径：{}", filePath);
            return JsonResult.ok(filePath);

        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
        }
        return JsonResult.ok("文件上传失败");
    }
}
